<?php
namespace api\modules\v1\controllers;
use api\common\controllers\UserController as U;
use api\modules\v1\models\Like;
use api\modules\v1\models\News;
use backend\models\User;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
use Yii;

class MsgController extends U
{
    public $modelClass = 'api\modules\v1\models\Msg';
    public $type = '';//点赞类型 1:针对主文章赞 2:针对评论赞


    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'],$actions['update'], $actions['create'], $actions['delete'], $actions['view']); //卸载操作
        return $actions;
    }


    /*
     * 获取消息列表
     * @param $id
     * @param $catid
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionList($type){
        $model = new $this->modelClass();
        $isread = Yii::$app->request->get('isread','');
        return $model->getList($type,$isread);
    }

    /*
     * 获取消息详情
     * @param $m_id
     * @return mixed
     */
    public function actionInfo($m_id){
        $modelClass = $this->modelClass;
        $Model = new $modelClass();
        return $Model->getInfo();
    }

    /*
     * 标记已读
     */
    public function actionRead(){
        $m_id = Yii::$app->request->post('m_id');
        if(empty($m_id)) throw new HttpException(401,'参数m_id不能为空',0);
        $modelClass = $this->modelClass;
        $model = new $modelClass();
        $data = $model->find()->select('m_id')->where('m_id in ('.$m_id.') and take_uid = '.Yii::$app->user->identity->id)->asArray()->column();
        if(count($data) == 0 ){
            throw new HttpException(401,'请勿非法提交',0);
        }
        $ids = implode(',',$data);
        if(false !== $model->updateAll(['isread'=>1],'m_id in ('.$ids.')')){
            return [
                "message"=>"已读标记成功!",
            ];
        }elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('由于不明原因未能创建对象.');
        }else{
            throw new HttpException(401,array_values($model->getFirstErrors())[0],0);
        }
    }

    /*
     * 删除消息
     * @return array
     * @throws HttpException
     * @throws ServerErrorHttpException
     */
    public function actionDel(){
        $m_id = Yii::$app->request->post('m_id');
        if(empty($m_id)) throw new HttpException(401,'参数m_id不能为空',0);
        $modelClass = $this->modelClass;
        $model = new $modelClass();

        if(!$model->findOne(['m_id'=>$m_id,'take_uid'=>Yii::$app->user->identity->id])){
            throw new HttpException(401,'请勿非法提交m_id',0);
        }

        if($model->deleteAll(['m_id'=>$m_id,'take_uid'=>Yii::$app->user->identity->id])){
            return [
                "message"=>"消息删除成功!",
            ];
        }elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('由于不明原因未能创建对象.');
        }else{
            throw new HttpException(401,array_values($model->getFirstErrors())[0],0);
        }
    }
}